package org.jiucheng.magpiebridge.transfer.aio;

import java.nio.channels.CompletionHandler;

/**
 * 
 * @author jiucheng
 *
 */
public class TransferWriteCompletionHandler implements CompletionHandler<Integer, TransferAttachment> {

	public void completed(Integer result, TransferAttachment attachment) {
		if (attachment.getWriteByteBuffer().hasRemaining()) {
			attachment.getClient().write(attachment.getWriteByteBuffer(), attachment, this);
			return;
		}
		attachment.writed.compareAndSet(true, false);
		
		if (attachment.isFailed()) {
			attachment.close();
		}
	}
	
	public void failed(Throwable exc, TransferAttachment attachment) {
		attachment.writed.compareAndSet(true, false);
		attachment.close();
	}
}
